package com.ruoyi.system.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.service.ISysAttributeDataService;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SysAttributeDataServiceImpl implements ISysAttributeDataService {

    private final RestTemplate restTemplate = new RestTemplate();
    private final ObjectMapper objectMapper = new ObjectMapper();


    @Override
    public List<List<String>> fetchAttributeList() {
        String parentId = "774643088755793920"; // Default parentId, can be modified as needed
        String url = "https://dme.cn-north-4.huaweicloud.com/rdm_ab943c84d62f49d8bf405861d2d0ef46_app/services/rdm/basic/api/exaDefinitionDir/queryExaDefinitionDirChildren?parentId=" + parentId;
        List<List<String>> result = new ArrayList<>();

        try {
            // Load the token file from the classpath
            ClassLoader classLoader = getClass().getClassLoader();
            Path tokenPath = Paths.get(classLoader.getResource("token.txt").toURI());
            String token = new String(Files.readAllBytes(tokenPath), StandardCharsets.UTF_8).trim();

            // Set up headers
            HttpHeaders headers = new HttpHeaders();
            headers.set("X-Auth-Token", token);

            // Create the request entity
            HttpEntity<String> entity = new HttpEntity<>(headers);

            // Make the GET request with headers
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);

            // Parse the JSON response
            JsonNode rootNode = objectMapper.readTree(response.getBody());
            JsonNode dataNode = rootNode.path("data");

            // Extract "children" and their details
            if (dataNode.isArray()) {
                for (JsonNode parentNode : dataNode) {
                    JsonNode childrenNode = parentNode.path("children");
                    if (childrenNode.isArray()) {
                        for (JsonNode childNode : childrenNode) {
                            List<String> childDetails = new ArrayList<>();
                            childDetails.add(childNode.path("id").asText());
                            childDetails.add(childNode.path("name").asText());
                            childDetails.add(childNode.path("nameEn").asText());
                            childDetails.add(childNode.path("description").asText());
                            childDetails.add(childNode.path("descriptionEn").asText());
                            childDetails.add(childNode.path("businessObject").path("type").asText());
                            result.add(childDetails);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }


    @Override
    public Object createAttribute(String name, String description, String nameEn, String descriptionEn, String type) {
        // Validate the type parameter
        if (!"STRING".equalsIgnoreCase(type) && !"DECIMAL".equalsIgnoreCase(type)) {
            throw new IllegalArgumentException("Invalid type: " + type + ". Allowed values are 'STRING' or 'DECIMAL'.");
        }

        Object response = null;
        String url = "https://dme.cn-north-4.huaweicloud.com/rdm_ab943c84d62f49d8bf405861d2d0ef46_app/services/rdm/basic/api/EXADefinition/create";

        try {
            // Load the token file from the classpath
            ClassLoader classLoader = getClass().getClassLoader();
            Path tokenPath = Paths.get(classLoader.getResource("token.txt").toURI());
            String token = new String(Files.readAllBytes(tokenPath), StandardCharsets.UTF_8).trim();

            // Set up headers
            HttpHeaders headers = new HttpHeaders();
//            headers.set("X-Auth-Token", token);
            headers.set("Content-Type", "application/json");

            // Determine the constraint based on the type
            String constraint;
            if ("STRING".equalsIgnoreCase(type)) {
                constraint = "{\"multiValue\":false,\"notnull\":false,\"variable\":true,\"stockInDB\":true,\"graphIndex\":false,\"graphLabel\":\"\",\"secretLevel\":\"internal\",\"associationType\":\"STRONG\",\"index\":false,\"length\":\"100\",\"caseMode\":\"DEFAULT\",\"optionalValue\":\"LEGAL_VALUE_TYPE\",\"legalValueType\":\"\",\"encryption\":false}";
            } else if ("DECIMAL".equalsIgnoreCase(type)) {
                constraint = "{\"associationType\":\"STRONG\",\"caseMode\":\"DEFAULT\",\"compose\":false,\"encryption\":false,\"graphIndex\":false,\"index\":false,\"legalValueType\":\"\",\"length\":0,\"multiValue\":false,\"notnull\":false,\"optionalValue\":\"LEGAL_VALUE_TYPE\",\"precision\":2,\"range\":\"\",\"secretLevel\":\"internal\",\"stockInDB\":true,\"variable\":true}";
            } else {
                throw new IllegalArgumentException("Unsupported type: " + type);
            }

            // Create the request body
            Map<String, Object> folder = new HashMap<>();
            folder.put("id", "774643088755793920");
            folder.put("clazz", "Folder");

            Map<String, Object> params = new HashMap<>();
            params.put("tagIds", new String[]{});
            params.put("tenant", new HashMap<>());
            params.put("name", name);
            params.put("description", description);
            params.put("type", type);
            params.put("descriptionEn", descriptionEn);
            params.put("nameEn", nameEn);
            params.put("disableFlag", false);
            params.put("category", "");
            params.put("eosTime", null);
            params.put("constraint", constraint);
            params.put("folder", folder);
            params.put("defaultValue", null);

            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("params", params);

            // Create the request entity
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

            // Make the POST request
            ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
            response = objectMapper.readValue(responseEntity.getBody(), Object.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return response;
    }


    @Override
    public Object deleteAttribute(String id) {
        Object response = null;
        String url = "https://dme.cn-north-4.huaweicloud.com/rdm_ab943c84d62f49d8bf405861d2d0ef46_app/services/rdm/basic/api/EXADefinition/batchDelete";

        try {
            // Load the token file from the classpath
            ClassLoader classLoader = getClass().getClassLoader();
            Path tokenPath = Paths.get(classLoader.getResource("token.txt").toURI());
            String token = new String(Files.readAllBytes(tokenPath), StandardCharsets.UTF_8).trim();

            // Set up headers
            HttpHeaders headers = new HttpHeaders();
            headers.set("X-Auth-Token", token);
            headers.set("Content-Type", "application/json");

            // Create the request body
            Map<String, Object> params = new HashMap<>();
            params.put("ids", new String[]{id});

            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("params", params);

            // Create the request entity
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

            // Make the POST request
            ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
            response = objectMapper.readValue(responseEntity.getBody(), Object.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return response;
    }




    @Override
    public Object updateAttribute(String id, String description, String descriptionEn) {
        String url = "https://dme.cn-north-4.huaweicloud.com/rdm_ab943c84d62f49d8bf405861d2d0ef46_app/services/rdm/basic/api/EXADefinition/update";
        Object response = null;

        try {
            // Load the token file from the classpath
            ClassLoader classLoader = getClass().getClassLoader();
            Path tokenPath = Paths.get(classLoader.getResource("token.txt").toURI());
            String token = new String(Files.readAllBytes(tokenPath), StandardCharsets.UTF_8).trim();

            // Set up headers
            HttpHeaders headers = new HttpHeaders();
            headers.set("X-Auth-Token", token);
            headers.set("Content-Type", "application/json");

            // Create the request body
            Map<String, Object> folder = new HashMap<>();
            folder.put("id", "774643088755793920");
            folder.put("clazz", "Folder");

            Map<String, Object> tenant = new HashMap<>();
            tenant.put("id", "-1");

            Map<String, Object> params = new HashMap<>();
            params.put("tagIds", new String[]{});
            params.put("tenant", tenant);
            params.put("name", "度");
            params.put("description", description);
            params.put("type", "STRING");
            params.put("descriptionEn", descriptionEn);
            params.put("nameEn", "du");
            params.put("disableFlag", false);
            params.put("category", "");
            params.put("eosTime", null);
            params.put("constraint", "{\"multiValue\":false,\"notnull\":false,\"variable\":true,\"stockInDB\":true,\"graphIndex\":false,\"graphLabel\":\"\",\"secretLevel\":\"internal\",\"associationType\":\"STRONG\",\"index\":false,\"length\":100,\"caseMode\":\"DEFAULT\",\"optionalValue\":\"LEGAL_VALUE_TYPE\",\"legalValueType\":\"\",\"encryption\":false}");
            params.put("id", id);
            params.put("folder", folder);
            params.put("defaultValue", null);
            params.put("needSetNullAttrs", new String[]{"eosTime", "defaultValue"});

            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("params", params);

            // Create the request entity
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

            // Make the POST request
            ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
            response = objectMapper.readValue(responseEntity.getBody(), Object.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return response;
    }

    @Override
    public List<List<String>> searchAttribute(String searchString) {
        // Split the search string by spaces
        String[] searchParts = searchString.split("\\s+");

        // Fetch all attributes
        List<List<String>> childrenDetails = this.fetchAttributeList();

        // Filter results
        List<List<String>> filteredDetails = new ArrayList<>();
        for (List<String> data : childrenDetails) {
            if (data.size() > 1) {
                for (String part : searchParts) {
                    if (data.get(1).contains(part)) {
                        filteredDetails.add(data);
                        break; // Avoid adding the same data multiple times
                    }
                }
            }
        }

        // Return filtered results
        return filteredDetails;
    }
}